/**
 * 微信广告.
 */


let BannerAdUtils = {
    _gBanner: null,
    _bannerState:false, // banner 是否应该显示

    _bLoaded:false, // 是否加载成功
    systemInfo: null,

    // 控制广告是否刷新. 使用显示次数来调整
    _showedCount:0, // 已经显示的次数

    _requestBanner() {

        if (!wxAds.isInited()) {
            throw new Error(`请先 调用 wxAds.init(bannerAdId,intersisterAdId,videoAdId) 进行初始化. `);
        }

        if (!this.systemInfo) {
            this.systemInfo = wx.getSystemInfoSync();
            console.log('this.systemInfo:', this.systemInfo);
        }

        let windowWidth = this.systemInfo.screenWidth;
        let windowHeight = this.systemInfo.screenHeight;

        let targetBannerAdWidth = windowWidth;
        let left = (windowWidth - targetBannerAdWidth) / 2;
        console.log('left:', left);

        let self = this;

        // 创建一个居于屏幕底部正中的广告
        let bannerAd = wx.createBannerAd({
            adUnitId: wxAds.getBannerAdId(),
            style: {
                width: targetBannerAdWidth,
                top: windowHeight - (targetBannerAdWidth / 16) * 9, // 根据系统约定尺寸计算出广告高度
                left: left,
            },
        });

        bannerAd.onResize((size) => {
            // good
            console.log(size.width, size.height);
            bannerAd.style.top = windowHeight - size.height;
            bannerAd.style.left = (windowWidth - size.width) / 2;

            // bad，会触发死循环
            // bannerAd.style.width++;
        });

        bannerAd.onLoad(() => {
            console.log('Banner 加载成功...');
            self._bLoaded = true;
            if(self.getBannerState()){
                bannerAd
                    .show()
                    .then(() => {
                        console.log("广告显示成功");
                    })
                    .catch((err) => {
                        console.log("广告组件出现问题", err);
                    });
            }
        });
        bannerAd.onError((err) => {
            console.log('Banner 加载失败... err:', err);
            self._bLoaded = false;
        });
        this._gBanner = bannerAd;
    },

    _removeBanner() {
        if (this._gBanner) {
            this._gBanner.destroy();
            this._gBanner = null;
            console.log('_removeBanner success!');
        }
    },

    getBannerState(){
        return this._bannerState;
    },

    //---------------------------------------
    // apis
    showBannerAd() {

        this._bannerState = true;

        if (!wx.createBannerAd) {
            return;
        }

        if (this._gBanner) {
            if(this._bLoaded){
                this._showedCount++;

                // 针对泡泡龙
                // 判断是否应该切换广告
                let refreshCount = ShSdk.GameConfig.getServerCfg().adsRefreshInterval;
                if(this._showedCount % refreshCount === 0){
                    // 需要刷新显示广告
                    this._removeBanner();
                    this._requestBanner();
                }else{
                    this._gBanner.show();
                }
            }else{
                console.log('banner加载中,但是还没有加载成功!');
            }
        } else {
            this._requestBanner();
        }
    },

    hideBanner() {
        this._bannerState = false;
        if(this._gBanner){
            this._gBanner.hide();
        }
    }
};

let InterstitialAdUtils = {
    _gInterAd: null,

    _removeInterAd() {
        if (this._gInterAd) {
            this._gInterAd.destroy();
            this._gInterAd = null;
            console.log('remove interAd success!');
        }
    },

    _requestInterAd() {
        if (!wxAds.isInited()) {
            throw new Error(`请先 调用 wxAds.init(bannerAdId,intersisterAdId,videoAdId) 进行初始化. `);
        }
        const interstitialAd = wx.createInterstitialAd({
            adUnitId: wxAds.getIntersistAdId(),
        });
        interstitialAd
            .load()
            .then(() => {
                interstitialAd.show();
            })
            .catch((err) => {
                console.log(err);
            });

        interstitialAd.onClose(() => {
            this._removeInterAd();
        });

        this._gInterAd = interstitialAd;
    },

    //-----------------------------
    // apis
    showInterstialAd() {

        if (!wx.createInterstitialAd) {
            return;
        }

        if (this._gInterAd) {
            this._removeInterAd();
            setTimeout(this._requestInterAd.bind(this), 50);
        } else {
            this._requestInterAd();
        }
    }
};

let VideoAdUtils = {
    _cacheSuccess: false,
    _gVideoAd: null,
    _videoCallback: null,

    _createVideoAd() {

        if (!wxAds.isInited()) {
            throw new Error(`请先 调用 wxAds.init(bannerAdId,intersisterAdId,videoAdId) 进行初始化. `);
        }

        let videoAd = wx.createRewardedVideoAd({
            adUnitId: wxAds.getVideoAdId(),
        });
        videoAd.onLoad(() => {
            console.log('激励视频加载成功');
            this._cacheSuccess = true;
        });

        videoAd.onError(err => {
            console.log('激励视频加载失败:', err);
            cc.director.resume(); // 可能是播放异常
            this._cacheSuccess = false;
        });

        videoAd.onClose((res) => {

            cc.director.resume();

            let complete = false;
            if (res.isEnded) {
                // 给予奖励
                // TODO: 给与视频奖励
                complete = true;
            }

            console.log('激励视频播放状况:', complete);

            if (this._videoCallback) {

                // 视频播放完毕
                if (complete) {
                    this._videoCallback(ShSdk.OP_PLAY_VIDEO);
                } else {
                    // 视频还没有播放完毕
                    window.ShSdk.videoUnFinishTip('完全观看才能获取奖励.');
                }
            }

            this.cacheVideoAd();
        });
        this._gVideoAd = videoAd;
    },

    //---------------------------------
    // apis
    // 游戏启动后
    cacheVideoAd() {
        if (!wx.createRewardedVideoAd) {
            return;
        }

        if (this._gVideoAd) {
            this._gVideoAd.load();
        } else {
            this._createVideoAd();
        }
    },

    showVideoAd(videoCb) {

        this._videoCallback = videoCb;

        if (!this._gVideoAd) {
            this.cacheVideoAd();
            return;
        }

        if (this._cacheSuccess) {
            this._gVideoAd.show().then(() => {
                // 暂停游戏引擎
                cc.director.pause();
            });
        } else {
            this.cacheVideoAd();
        }
    },

    videoCachedSuccess() {
        return this._cacheSuccess;
    }
};

let GridAdUtils = {

    _gGridAd: null,
    _bCanShow: false,

    showGridAd(obj) {
        this._bCanShow = true;

        // 将游戏中的数据 转换成 canvas 中的数据
        let x = obj.x || 0;
        let y = obj.y || 0;
        let width = obj.width || 160;
        let height = obj.height || 160;
        let adCount = obj.count || 8;
        let theme = obj.theme || 'black';

        let posInCanvas = wxAds.ccPosToCanvas({x: x, y: y});
        let sizeInCanvas = wxAds.ccSizeToCanvas({width: width, height: height});
        console.log('posInCanvas:',posInCanvas);
        console.log('sizeInCanvas:',sizeInCanvas);

        if (!this._gGridAd) {
            let self = this;
            if (wx.createGridAd) {
                console.log('创建格子广告..........');
                this._gGridAd = wx.createGridAd({
                    adUnitId: wxAds.getGridAdId(),
                    // adIntervals: 60, 广告不刷新
                    style: {
                        left: ~~(posInCanvas.x - sizeInCanvas.width / 2),
                        top: ~~(posInCanvas.y - sizeInCanvas.height / 2),
                        width: ~~sizeInCanvas.width,
                        height: ~~sizeInCanvas.height,
                    },
                    adTheme: theme,
                    gridCount: adCount,
                });
                this._gGridAd.onLoad(() => {
                    if (this._bCanShow) {
                        this._gGridAd.show().then(()=>{
                            // 执行回调
                            if(obj.success){
                                let realWidth = self._gGridAd.style.realWidth;
                                let realHeight = self._gGridAd.style.realHeight;
                                let cx = self._gGridAd.style.left + realWidth/2;
                                let cy = self._gGridAd.style.top + realHeight/2;
                                let ccpos = wxAds.canvasPosToCC({x:cx,y:cy});
                                console.log(`success-->realWidth:${realWidth},realHeight:${realHeight}`);
                                let sizeInCC = wxAds.canvasSizeToCC({width:realWidth,height:realHeight});
                                obj.success(ccpos.x,ccpos.y,sizeInCC.width,sizeInCC.height);
                            }
                        });
                    }
                });
                this._gGridAd.onResize((res)=>{
                    let realWidth = res.width;
                    let realHeight = res.height;
                    console.log(`realWidth:${realWidth},realHeight:${realHeight}`);
                    this._gGridAd.style.left = ~~(posInCanvas.x - realWidth/2);
                    this._gGridAd.style.top = ~~(posInCanvas.y - realHeight/2);
                });

                this._gGridAd.onError((res) => {
                    console.warn(`errMsg:${res.errMsg},errCode:${res.errCode}`);
                    this._bCanShow = false;
                });
            } else {
                console.log(`wxsdkVersion:${wxsdkVersion},还不支持Grid广告`);
            }
        } else {
            if (this._bCanShow) {
                // let style = this._gGridAd.style;
                // style.lef = ~~(posInCanvas.x - sizeInCanvas.width / 2);
                // style.top = ~~(posInCanvas.y - sizeInCanvas.height / 2);
                // style.width = ~~sizeInCanvas.width;
                // style.height = ~~sizeInCanvas.height;
                this._gGridAd.show().then(()=>{
                    // 执行回调
                    if(obj.success){
                        let realWidth = self._gGridAd.style.realWidth;
                        let realHeight = self._gGridAd.style.realHeight;
                        let cx = self._gGridAd.style.left + realWidth/2;
                        let cy = self._gGridAd.style.top + realHeight/2;
                        let ccpos = wxAds.canvasPosToCC({x:cx,y:cy});
                        console.log(`success-->realWidth:${realWidth},realHeight:${realHeight}`);
                        let sizeInCC = wxAds.canvasSizeToCC({width:realWidth,height:realHeight});
                        obj.success(ccpos.x,ccpos.y,sizeInCC.width,sizeInCC.height);
                    }
                });
            }
        }
    },

    hideGridAd() {
        this._bCanShow = false;
        if (this._gGridAd) {
            this._gGridAd.destroy();
            this._gGridAd = null;
        }
    },

};

let wxAds = {
    _bInited: false,
    _BannerAdId: null,
    _IntersisterAdId: null,
    _VideoAdId: null,
    _GridAdId: null,
    _sysInfo: null,

    BannerAdUtils: BannerAdUtils,
    InterstitialAdUtils: InterstitialAdUtils,
    VideoAdUtils: VideoAdUtils,
    GridAdUtils: GridAdUtils,

    init(bannerAdId, interstitialAdId, videoAdId, gridAdId) {
        if (this._bInited) {
            return;
        }
        this._BannerAdId = bannerAdId;
        this._IntersisterAdId = interstitialAdId;
        this._VideoAdId = videoAdId;
        this._GridAdId = gridAdId;
        this._sysInfo = wx.getSystemInfoSync();
        this._bInited = true;
    },

    // 需要将游戏坐标转换成 广告坐标
    // pos 参考的是 中心点位屏幕中心的坐标系
    ccPosToCanvas(pos) {
        const winSize = ShSdk.getWinSize();
        let x = this._sysInfo.screenWidth * (pos.x + winSize.width / 2) / winSize.width;
        let y = this._sysInfo.screenHeight - this._sysInfo.screenHeight * (pos.y + winSize.height / 2) / winSize.height;
        return {x: x, y: y};
    },


    ccSizeToCanvas(size) {
        const winSize = ShSdk.getWinSize();
        let w = size.width * this._sysInfo.screenWidth / winSize.width;
        let h = size.height * this._sysInfo.screenHeight / winSize.height;
        return {width: w, height: h};
    },

    //  canvas里面的宽高转换成游戏中的宽高
    canvasSizeToCC(size){
        const winSize = ShSdk.getWinSize();
        let w = size.width *  winSize.width / this._sysInfo.screenWidth;
        let h = size.height *  winSize.height / this._sysInfo.screenHeight;
        return {width: w, height: h};
    },

    canvasPosToCC(pos){
        const winSize = ShSdk.getWinSize();
        let x = pos.x * winSize.width / this._sysInfo.screenWidth - 0.5 * winSize.width;
        let y = 0.5 * winSize.height - pos.y * winSize.height / this._sysInfo.screenHeight;
        return {x: x, y: y};
    },

    isInited() {
        return this._bInited;
    },

    getBannerAdId() {
        return wxAds._BannerAdId;
    },

    getIntersistAdId() {
        return wxAds._IntersisterAdId;
    },

    getVideoAdId() {
        return wxAds._VideoAdId;
    },

    getGridAdId() {
        return wxAds._GridAdId;
    }
};

export default wxAds;
